﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TileNotificationsPack;
using Windows.ApplicationModel.Background;
using Windows.UI.Notifications;

namespace LiveTiles.Tasks
{
   public sealed class LiveTileTask : IBackgroundTask
   {
      public void Run(IBackgroundTaskInstance taskInstance)
      {
         // Get a deferral, to prevent the task from closing prematurely 
         // while asynchronous code is still running.
         BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

         UpdateTile();

         // Inform the system that the task is finished.
         deferral.Complete();
      }

      private static void UpdateTile()
      {
         var updater = TileUpdateManager.CreateTileUpdaterForApplication();
         updater.EnableNotificationQueue(true);
         updater.Clear();

         var imgsrc = new string[] {
            "ms-appx:///Images/Default.png",
            "ms-appx:///Images/Downloads.png",
            "ms-appx:///Images/Email_Chat.png",
            "ms-appx:///Images/Mail.png",
            "ms-appx:///Images/User.png",
         };

         for (int i = 0; i < 5; ++i)
         {
            try
            {
               var tiles = new TileCollection()
               {
                  new TileSquare150x150Image() {
                     Binding = new TileBinding() { Branding = TileBranding.name },
                     Image = new TileImage() { Src = imgsrc[i], Alt = imgsrc[i] }
                  },
                  new TileWide310x150ImageAndText01(){
                     Image = new TileImage() { Src = imgsrc[i], Alt = imgsrc[i] },
                     Text = string.Format("this is notification #{0}", i+1)
                  },
                  new TileSquare310x310ImageAndTextOverlay02() {
                     Binding = new TileBinding() { Branding = TileBranding.none },
                     Image = new TileImage() { Src = imgsrc[i], Alt = imgsrc[i] },
                     Text = string.Format("this is notification #{0}", i+1),
                     Text2 = string.Format("and this is a description for notification #{0}", i+1)
                  }
               };

               updater.Update(tiles);
            }
            catch (Exception ex)
            {
               Debug.WriteLine(ex.Message);
            }
         }
      }
   }
}
